package cn.pconline.autoclub.web;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubPv;
import cn.pconline.autoclub.entity.ClubVisitor;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ClubPvService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.ClubVisitorService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author ppc
 */
@Controller
public class VisitorController {

    @Autowired
    private UserAuth userAuth;
    @Autowired
    private ClubVisitorService clubVisitorService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private ClubPvService clubPvService;
    private static final int SUCCESS_CODE = 0;
    private static final int FAIL_CODE = -1;
    private static final int DEFAULT_PAGE_SIZE = 20;
    private static final int MAX_PAGE_SIZE = 100;

    @RequestMapping(value = "/visitor/addUserVisitor.do", method = RequestMethod.POST)
    @ResponseBody
    public void addUserVisitor(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        if (clubId > 0 && clubService.getValidClub(clubId) != null) {
            User user = userAuth.getUser(req, resp);
            if (user != null && user.getUid() > 0) {
                ClubVisitor clubVisitor = new ClubVisitor();
                clubVisitor.setClubId(clubId);
                clubVisitor.setUserId(user.getUid());
                clubVisitor.setVisitorDate(new Date());
                clubVisitor.setCreateAt(new Date());
                int count = clubVisitorService.createOrUpdateVisitor(clubVisitor);
                if (count > 0) {
                    printSuccessMsg(resp, "创建成功", null);
                } else {
                    printErrorMsg(resp, "创建失败", null);
                }
            } else {
                printErrorMsg(resp, "请先登录", null);
            }
        } else {
            printErrorMsg(resp, "clubId参数有误", null);
        }


    }

    @RequestMapping(value = "/visitor/addPv.do", method = RequestMethod.POST)
    @ResponseBody
    public void addPv(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        if (clubId > 0) {
            clubPvService.savePv(clubId, DateUtils.getTodayYmd());
            printSuccessMsg(resp, "创建成功", null);
        } else {
            printErrorMsg(resp, "clubId参数有误", null);
        }
    }

    private void printSuccessMsg(HttpServletResponse resp, String msg, String callback) {
        JSONObject obj = new JSONObject();
        obj.put("code", SUCCESS_CODE);
        obj.put("message", msg);
        printMsg(resp, obj.toJSONString(), callback);
    }

    private void printErrorMsg(HttpServletResponse resp, String msg, String callback) {
        JSONObject obj = new JSONObject();
        obj.put("code", FAIL_CODE);
        obj.put("message", msg);
        printMsg(resp, obj.toJSONString(), callback);
    }

    private void printMsg(HttpServletResponse resp, String msg, String callback) {
        try {
            PrintWriter print = resp.getWriter();
            if (StringUtils.isBlank(callback)) {
                print.println(msg);
            } else {
                print.println(callback + "(" + msg + ")");
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            Logger.getLogger(VisitorController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * 获取车友会访客记录接口
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/visitor/listVisitorByClub.do", method = RequestMethod.GET)
    public void listVisitorByClub(HttpServletRequest req, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", DEFAULT_PAGE_SIZE, 1, MAX_PAGE_SIZE);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            printErrorMsg(resp, "车友会不存在", null);
            return;
        }
        Pager<ClubVisitor> pager = clubVisitorService.listVisitorByClubId(clubId, pageNo, pageSize);
        JSONObject obj = new JSONObject();
        JSONArray array = new JSONArray();
        if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            for (ClubVisitor clubVisitor : pager.getResultList()) {
                JSONObject o = new JSONObject();
                o.put("user_id", clubVisitor.getUserId());
                o.put("clubId", clubVisitor.getClubId());
                o.put("visitorDate", clubVisitor.getVisitorDate());
                array.add(o);
            }
        }
        obj.put("data", array);
        obj.put("code", SUCCESS_CODE);
        printMsg(resp, obj.toJSONString(), null);
    }
}
